import {
	SERVERTAPI
} from '@/config/index.js'
import store from '@/store/index.js'

/**
 * 上传图片视频
 * @param {type}  type 上传类型
 */
function uploadImgVideo(type = 'image', maxImage) {
	return new Promise((resolve, rejects) => {
		if (type == 'image') {
			uni.chooseImage({
				count: maxImage,
				sizeType: ['compressed'],
				sourceType: ['album'],
				success: function(res) {
					uni.showLoading({
						title: '上传中'
					})
					var tempFilePaths = res.tempFilePaths;
					// 上传文件
					uploadFile(tempFilePaths).then(res => {
						resolve(res)
					}).catch(error => {
						rejects(error)
					}).finally(() => {
						uni.hideLoading()
					})
				}
			});
		} else if (type == 'video') {
			uni.chooseVideo({
				sourceType: ['album'],
				success: function(res) {
					uni.showLoading({
						title: '上传中'
					})
					var tempFilePath = res.tempFilePath;
					// 上传文件
					uploadFile([tempFilePath]).then(res => {
						resolve(res)
					}).catch(error => {
						rejects(error)
					}).finally(() => {
						uni.hideLoading()
					})
				}
			});
		}
	})
}


/**
 * 上传文件
 * @param {type} list 文件数组
 */
function uploadFile(list) {
	return Promise.all(list.map(item => {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: `${SERVERTAPI}api/upload/img`,
				filePath: item,
				name: 'pic',
				header: {
					'Token': store.state.userInfo.token
				},
				success: function(res) {
					resolve(JSON.parse(res.data).data);
				},
				fail: function(res) {
					uni.hideLoading()
					reject(res);
				}
			});
		});
	}))
}

/**
 * 上传文件
 * @param {type} list 文件数组
 */
function uploadMp3File(list) {
	return Promise.all(list.map(item => {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: `${SERVERTAPI}api/upload/files`,
				filePath: item,
				name: 'pic',
				header: {
					// 'Token': store.state.userInfo.token
				},
				success: function(res) {
					resolve(JSON.parse(res.data).data);
				},
				fail: function(res) {
					uni.hideLoading()
					reject(res);
				}
			});
		});
	}))
}
/**
 * 上传语音
 *  
 */
// function checkPermission() {
// 	return new Promise(async (resolve, reject) => {
// 		// 先判断os
// 		let permisionState = false
// 		let os = uni.getSystemInfoSync().osName;
// 		if (os == 'ios') {
// 			permisionState = await permision.judgeIosPermission('record');
// 		} else {
// 			permisionState = await permision.requestAndroidPermission('android.permission.RECORD_AUDIO');
// 		}

// 		if (permisionState !== true && permisionState !== 1) {
// 			uni.showToast({
// 				title: '请先授权使用录音',
// 				icon: 'none'
// 			});
// 			reject()
// 		}else{
// 			resolve()
// 		}
// 	})
// }
function checkPermission() {
    return new Promise(async (resolve, reject) => {
        try {
            // 检测当前环境是否为 H5
            if (typeof window !== 'undefined' && navigator.mediaDevices) {
                // 请求录音权限
                await navigator.mediaDevices.getUserMedia({ audio: true });
                resolve(); // 权限获取成功
            } else {
                // 获取操作系统信息
                let os = uni.getSystemInfoSync().osName;
                let permissionState;

                // 根据操作系统请求权限
                if (os === 'ios') {
                    permissionState = await permision.judgeIosPermission('record');
                } else {
                    permissionState = await permision.requestAndroidPermission('android.permission.RECORD_AUDIO');
                }

                // 检查权限状态
                if (permissionState !== true && permissionState !== 1) {
                    uni.showToast({
                        title: '请先授权使用录音',
                        icon: 'none'
                    });
                    reject(new Error('Permission denied'));
                } else {
                    resolve();
                }
            }
        } catch (error) {
            // 处理权限请求中的错误
			console.log(error,'eeeeeeeeeeee')
            uni.showToast({
                title: '请求权限时出错',
                icon: 'none'
            });
            reject(error);
        }
    });
}
//时间戳转换
function timestampToDate(timestamp) {
  // 将时间戳转换为毫秒
  const date = new Date(timestamp * 1000);

  // 格式化日期
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  // 返回格式化的日期时间字符串
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

export {
	uploadImgVideo,
	uploadFile,
	uploadMp3File,
	checkPermission,
	timestampToDate
}